package com.huafeng.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huafeng.commonutil.CheckUtils;
import com.huafeng.mapper.SysPostMapper;
import com.huafeng.model.base.Result;
import com.huafeng.model.entity.SysPost;
import com.huafeng.model.vo.SysPostQueryVo;
import com.huafeng.service.SysPostService;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author 花风
 * @date 2023/8/19 11:20
 * @Description SysPostServiceImpl
 */
@Service
public class SysPostServiceImpl extends ServiceImpl<SysPostMapper, SysPost> implements SysPostService {
    private final ReentrantLock updateStatusLock = new ReentrantLock();

    @Override
    public Result querySysPostByPage(SysPostQueryVo sysPostQueryVo) {
        //创建分页对象
        Page<SysPost> sysPostPage = new Page<>(sysPostQueryVo.getPage(), sysPostQueryVo.getLimit());

        // 获取查询参数
        String name = sysPostQueryVo.getName();
        String postCode = sysPostQueryVo.getPostCode();

        // 创建条件查询对象
        QueryWrapper<SysPost> queryWrapper = new QueryWrapper<>();
        Map<String,String> params = new HashMap<>();
        params.put("name",name);
        params.put("post_code",postCode);
        queryWrapper = CheckUtils.checkParams(queryWrapper,sysPostQueryVo,params);

        // 分页查询
        sysPostPage = page(sysPostPage,queryWrapper);
        return Result.ok(sysPostPage);
    }

    @Override
    public Result updateStatus(Long id, Integer status) {
        updateStatusLock.lock();
        try {
            boolean update = this.update().set("status", status).eq("id", id).update();
            return CheckUtils.check(update);
        }finally {
            updateStatusLock.unlock();
        }
    }
}
